package cn.sangyy.gift.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.sangyy.gift.auth.client.LoginUserClient;
import cn.sangyy.gift.common.util.AjaxResult;
import cn.sangyy.gift.common.util.PageList;
import cn.sangyy.gift.common.util.code.CodeEnum;
import cn.sangyy.gift.constant.BaseConstant;
import cn.sangyy.gift.constant.MqConstant;
import cn.sangyy.gift.domain.LoginUser;
import cn.sangyy.gift.domain.User;
import cn.sangyy.gift.domain.UserInfo;
import cn.sangyy.gift.dto.PhoneRegisterDto;
import cn.sangyy.gift.exception.GiftAssert;
import cn.sangyy.gift.mapper.UserInfoMapper;
import cn.sangyy.gift.mapper.UserMapper;
import cn.sangyy.gift.query.UserQuery;
import cn.sangyy.gift.service.IPhoneVerifyCodeService;
import cn.sangyy.gift.service.IUserService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author sangyy
 * @since 2023-06-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private IPhoneVerifyCodeService phoneVerifyCodeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LoginUserClient loginUserClient;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public PageList<User> getPageList(UserQuery query) {
        Page<User> page = new Page<>(query.getPage(), query.getRows());
        List<User> data = userMapper.getList(page,query);
        return new PageList<>(page.getTotal(),data);
    }

    @Override
    public void offById(Long id) {
        userMapper.offById(id);
    }

    @Override
    public void relieve(Long id) {
        userMapper.relieve(id);
    }

    @Override
    public void sendCodeByReg(String phone) {
        GiftAssert.assertStrNotBlank(phone, CodeEnum.REGISTER_MOBILE_NOT_EMPTY);
        String codeKey = BaseConstant.REGISTER_PHONE_CODE_IN_REDIS+phone;
        //发送短信验证码
        phoneVerifyCodeService.sendVerifyCode(phone,codeKey);
    }

    @Transactional
    @Override
    public void phoneRegister(PhoneRegisterDto dto) {
        String phone = dto.getPhone();
        String code = dto.getCode();
        String password = dto.getPassword();
        String codeKey = BaseConstant.REGISTER_PHONE_CODE_IN_REDIS+phone;
        String redisCode = (String)redisTemplate.opsForValue().get(codeKey);
        GiftAssert.assertStrNotBlank(redisCode,CodeEnum.REGISTER_MOBILE_CODE_NOT_EXIST);
        GiftAssert.assertStrEqIgnoreCase(code,redisCode,CodeEnum.CODE_ERROR);
        //保存数据
//        saveUserData(phone, password);
        //发送短信或者邮件给用户
        sendRegisterSuccessEmail(phone);
    }

    private void sendRegisterSuccessEmail(String phone) {
        rocketMQTemplate.asyncSend(MqConstant.REGISTER_SUCCESS_NOTE_TOPIC, phone, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("成功发送用户注册成功邮件给手机号为:"+ phone +"的用户。");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送注册成功邮件给用户失败！");
                throwable.printStackTrace();
            }
        });
    }

    private void saveUserData(String phone, String password) {
        //新增登录表
        LoginUser loginUser = new LoginUser();
        loginUser.setPassword(password);
        loginUser.setTel(phone);
        loginUser.setType(1);
        String username = UUID.randomUUID().toString();
        loginUser.setUsername(username);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        Long loginId = Long.valueOf(ajaxResult.getResultObj().toString());
        GiftAssert.assertNotNull(loginId,"网络异常！");
        //新增用户表
        User user = new User();
        user.setPassword(password);
        user.setBitState(BaseConstant.USER_BIT_STATE_NORMAL);
        user.setCreateTime(new Date());
        user.setLoginId(loginId);
        user.setPhone(phone);
        user.setSecLevel(1);
        userMapper.insert(user);
        //新增用户详情表
        UserInfo userInfo = new UserInfo();
        userInfo.setRegChannel(1);
        userInfo.setRegTime(new Date());
        userInfo.setNickName(username);
        userInfo.setPhone(phone);
        userInfo.setLevel(1);
        userInfo.setUserId(user.getId());
        userInfo.setCreateTime(new Date());
        userInfoMapper.insert(userInfo);
    }


}
